<template>
  <NUpload :show-file-list="false" action="" :custom-request="customRequest">
    <slot name="refrence" :data="uploading">
      <NButton>上传文件</NButton>
    </slot>
  </NUpload>
</template>
<script setup lang="ts">
import {
  NUpload,
  NButton,
  UploadCustomRequestOptions,
  useMessage,
} from "naive-ui";
import { ref, defineEmits } from "vue";
import { fetchUploadFileWithDeal, FileResult } from "~/api/file";
interface IUploadProps {
  scene: string;
  modelValue: string;
}
const uploading = ref({
  isLoading: false,
});
const message = useMessage();
const props = withDefaults(defineProps<IUploadProps>(), {
  scene: "",
  modelValue: "",
});
const uploadDoneData = ref<FileResult>({
  file_id: 0,
  path: "",
});
const emits = defineEmits(["update:modelValue"]);

const customRequest = ({
  file,
  data,
  headers,
  withCredentials,
  action,
  onFinish,
  onError,
  onProgress,
}: UploadCustomRequestOptions) => {
  if (!file.file) return;
  uploading.value.isLoading = true;
  fetchUploadFileWithDeal({
    file: file.file,
    sceneType: props.scene,
  })
    .then((r) => {
      uploadDoneData.value = r;
      emits("update:modelValue", uploadDoneData.value.file_id.toString());
    })
    .finally(() => {
      uploading.value.isLoading = false;
    });
};
</script>
<style lang="scss" scoped>
.n-input {
  background-color: transparent;
  border-radius: 12px;
}
</style>
